//
//  OpenLiveViewController.m
//  sklive
//
//  Created by Macx on 2017/5/2.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "OpenLiveViewController.h"
#import <CoreLocation/CoreLocation.h>

#import "YKMultiLevelTableView.h"

//AgoraLive
#import "LiveRoomViewController.h"
#import "SettingsViewController.h"


#import "EndLiveViewController.h"
#import "BlocksKit+UIKit.h"
#import "UIPlaceHolderTextView.h"
#import "UIImage+Additions.h"
#import "TCPushViewController.h"
#import "TCPusherModel.h"
#import "TCUploadHelper.h"
#import "TCLoginModel.h"
#import "TCMsgHandler.h"
#import "TCUserInfoModel.h"
#import "TCLiveListModel.h"
#import "UIView+Additions.h"
#import "TCUtil.h"
#if POD_PITU
//#import "TCPublishControllerEx.h"
#endif
#import "TCPushViewController_LinkMic.h"
#import "NSString+Common.h"
#if YOUTU_AUTH
#import "TCYTRealNameAuthViewController.h"
#endif

//BOOL g_bNeedEnterPushSettingView = NO;

#import "LiveServer.h"

//#import <ShareSDK/NSMutableDictionary+SSDKShare.h>
//#import <ShareSDKUI/ShareSDK+SSUI.h>

#import <SDImageCache.h>

#import "Share.h"

#define kTCMaxPushTitleLen        30


@interface OpenLiveViewController () <CLLocationManagerDelegate, UITextFieldDelegate, UIImagePickerControllerDelegate, LiveRoomVCDelegate, UINavigationControllerDelegate>

// 定位
@property (nonatomic, strong) CLLocationManager *locationManager;

// 相册照相机
@property (nonatomic, strong) UIImagePickerController *picker;
// 头像地址
@property (nonatomic, strong) NSString *imgStr;

@property (nonatomic, strong) YKMultiLevelTableView  *mutableTable;

@property (nonatomic, strong) NSMutableArray *tagArr;

@property (nonatomic, strong) NSString *tagId;

//AgoraLive property
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;

@end

@implementation OpenLiveViewController {
    TCLiveInfo *_liveInfo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleBroadcaster;
	
    // 获取直播标签
    [self GETliveTags];
    
    [self buildUI];
    
    // 进入房间主动打开定位
//    [self openLocate];
    
//    [self createImgPicker];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {

    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:bgImage];
    bgImage.backgroundColor = [UIColor blackColor];
    bgImage.image = [UIImage imageNamed:@"bg_alive"];
    bgImage.contentMode = UIViewContentModeScaleAspectFit;
    bgImage.tag = 1;
    
    
    UIView *darkBgImg = [[UIView alloc] initWithFrame:bgImage.bounds];
    [self.view addSubview:darkBgImg];
    darkBgImg.backgroundColor = [UIColor blackColor];
    darkBgImg.alpha = 0.4;
    
    NSArray *btnImgArr = @[@"placeHolder", @"placeHolder", @"live_start_close"];
    
    for (int i = 0; i < 3; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:btn];
        btn.frame = CGRectMake(SCREEN_WIDTH-SW(8)*(3-i), 20, SW(10), SW(10));
        btn.tag = 11+i;
        [btn setImage:[UIImage imageNamed:btnImgArr[i]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(headBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i != 2) {
            btn.hidden = YES;
        }
    }
    
    // 定位UI
    UIButton *locateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:locateBtn];
    [locateBtn setImage:[UIImage imageNamed:@"placeHolder"] forState:UIControlStateNormal];
    [locateBtn setTitle:@" 开启定位" forState:UIControlStateNormal];
    locateBtn.titleLabel.font = kUHSystemFontWithSize(14);
    [locateBtn addTarget:self action:@selector(openLocateAction:) forControlEvents:UIControlEventTouchUpInside];
    locateBtn.tag = 21;
    [locateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    CGSize locateSize = [LZCTools textSizeWithText:locateBtn.titleLabel.text font:kUHSystemFontWithSize(14)];
    locateBtn.frame = CGRectMake(20, 20+SW(40), locateSize.width+5+SW(16), SW(16));
    locateBtn.hidden = YES;
    
    // 添加cover
    UIButton *addCoverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:addCoverBtn];
    addCoverBtn.titleLabel.font = kUHSystemFontWithSize(16);
    addCoverBtn.frame = CGRectMake(self.view.center.x-SW(8) , SW(4), SW(4), SW(4));
    [addCoverBtn setImage:[UIImage imageNamed:@"placeHolder"] forState:UIControlStateNormal];
    addCoverBtn.imageEdgeInsets = UIEdgeInsetsMake(SW(4), SW(4), SW(4), SW(4));
    [addCoverBtn addTarget:self action:@selector(addConverAction:) forControlEvents:UIControlEventTouchUpInside];
    addCoverBtn.tag = 61;
    addCoverBtn.hidden = YES;
    
    // title
    UITextField *titleTF = [[UITextField alloc] init];
    [self.view addSubview:titleTF];
    titleTF.delegate = self;
    titleTF.tag = 41;
    titleTF.placeholder = @"给你的直播写个标题吧";
    [titleTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    titleTF.textColor = [UIColor whiteColor];
    titleTF.font = kUHSystemFontWithSize(16);
    titleTF.textAlignment = NSTextAlignmentCenter;
    CGFloat tfHeight = [LZCTools textSizeWithText:titleTF.placeholder font:titleTF.font].height;
    titleTF.frame = CGRectMake(0, self.view.center.y-tfHeight/2, SCREEN_WIDTH, tfHeight);
    
    // Tag
    UIButton *tagBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:tagBtn];
    [tagBtn setTitle:@"选择直播标签" forState:UIControlStateNormal];
    tagBtn.titleLabel.font = kUHSystemFontWithSize(16);
//    tagBtn.frame =
    CGSize tagSize = [LZCTools textSizeWithText:tagBtn.titleLabel.text font:kUHSystemFontWithSize(16)];
    tagBtn.frame = CGRectMake((SCREEN_WIDTH-tagSize.width)/2-5, titleTF.y+titleTF.height+20, tagSize.width+10, tagSize.height+5);
    tagBtn.layer.cornerRadius = 2;
    tagBtn.layer.masksToBounds = YES;
    tagBtn.layer.borderWidth = 1;
    tagBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [tagBtn addTarget:self action:@selector(clickTag:) forControlEvents:UIControlEventTouchUpInside];
    tagBtn.tag = 51;
    
   //    UIView *tagBgView = [[UIView alloc] initWithFrame:CGRectMake(0, tagBtn.y+tagBtn.height, SCREEN_WIDTH, SCREEN_HEIGHT-(tagBtn.y+tagBtn.height+10))];
//    [self.view addSubview:tagBgView];
//    tagBgView.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.5];
    
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:startBtn];
    [startBtn setTitle:@"开启直播" forState:UIControlStateNormal];
    [startBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    CGFloat btnHeight = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+SW(20);
    startBtn.frame = CGRectMake(SW(10), self.view.bounds.size.height-btnHeight-SW(20), SCREEN_WIDTH-SW(5), btnHeight);
    startBtn.backgroundColor = [UIColor colorWithHexString:UIMainColor alpha:1];
    startBtn.layer.cornerRadius = btnHeight/2;
    startBtn.layer.masksToBounds = YES;
    [startBtn addTarget:self action:@selector(startLiveAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    NSArray *shareArr = @[@"placeHolder", @"placeHolder", @"placeHolder", @"placeHolder", @"placeHolder", @"placeHolder"];
    NSArray *shareArr = @[@"live_start_weixin", @"live_start_friends", @"live_start_qq", @"live_start_zone", @"live_start_weibo"];
    CGFloat btnSize = (SCREEN_WIDTH-40)/5;
    for (int i = 0; i < shareArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:btn];
//        btn.frame = CGRectMake(20+btnSize*i, startBtn.y-10-btnSize, btnSize, btnSize);
        btn.frame = CGRectMake(20+btnSize*i, startBtn.y-10-btnSize, btnSize, btnSize);
        btn.tag = 31+i;
        [btn setImage:[UIImage imageNamed:shareArr[i]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}


#pragma mark ==========响应方法==========
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.mutableTable.hidden = YES;
}

/**
 选择直播标签
 */
- (void)clickTag:(UIButton *)sender {
    NSLog(@"选择直播标签");
    self.mutableTable.hidden = NO;
}
/**
 分享响应
 */
- (void)shareBtnAction:(UIButton *)btn {
    
    NSString *image = GetUserDefaule(USERINFO)[@"face"];
    NSString *sign = GetUserDefaule(USERINFO)[@"intro"];
    UITextField *roomTitleTF = [self.view viewWithTag:41];
	NSLog(@"title is %@", roomTitleTF.text);
    NSString *name = GetUserDefaule(USERINFO)[@"nickname"];
    NSString *title = [NSString stringWithFormat:@"%@ %@",roomTitleTF.text, sign];
    NSString *text = [NSString stringWithFormat:@"%@正在直播……", name];
    NSString *url = [NSString stringWithFormat:@"%@/mobile/download/a/hostUserId/%@", APIBackEndUrl, GetUserDefaule(USERINFO)[@"user_id"]];
	NSLog(@"url live is %@", url);
    NSDictionary *p = @{@"url":url,
                        @"title":title,
                        @"text":text,
                        @"img":image};
    
    if (btn.tag == 31) {
        [Share shareActionwx:p];
    }
    else if (btn.tag == 32) {
        [Share shareActionpyq:p];
    }
    else if (btn.tag == 33) {
        [Share shareActionqq:p];
    }
    else if (btn.tag == 34) {
        [Share shareActionqqZone:p];
    }
    else if (btn.tag == 35) {
        [Share shareActionwb:p];
    }
    
}

- (void)headBtnAction:(id)sender {
    
    UIButton *btn = sender;
    
    if (btn.tag == 11) {
        NSLog(@"美颜被点击了");
    }
    else if (btn.tag == 12) {
        NSLog(@"摄像头被点击了");

        [((UIButton *)[self.view viewWithTag:51]) setTitle:@"x" forState:UIControlStateNormal];
        ((UIImageView *)[self.view viewWithTag:1]).image = [UIImage imageNamed:@"placeHolder"];
        // 上传图片如果尚未成功，就重新执行此方法 延时
        self.imgStr = @"http://4klive.catrongzi.com/Uploads/image/1500431830/596ec5d68739e.png";
        ((UITextField *)[self.view viewWithTag:41]).text = @"小白开播";
        self.tagId = @"54";
        
        [self startLiveAction:nil];
        
    }
    else {
        NSLog(@"退出当前页面");
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}
- (void)addConverAction:(UIButton *)sender {
    
    self.mutableTable.hidden = YES;
    
    NSLog(@"添加封面");
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改直播封面" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"从相册中选择");
        
        self.picker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"拍照");
        
        self.picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        self.picker.mediaTypes =[UIImagePickerController availableMediaTypesForSourceType:self.picker.sourceType];
        [self presentViewController:self.picker animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

// 开启直播
- (void)startLiveAction:(id)sender {
    
    NSLog(@"开启直播");
    
    NSString *tagStr = ((UIButton *)[self.view viewWithTag:51]).titleLabel.text;
    
//    UIImageView *img = (UIImageView *)[self.view viewWithTag:1];
//    if ([img.image isEqual:[UIImage imageNamed:@"live_start_bg"]]) {
//        [HUDHelper alert:@"封面不能为空"];
//        return;
//    }
//    // 上传图片如果尚未成功，就重新执行此方法 延时
//    if (self.imgStr.length == 0) {
//        [self performSelector:@selector(startLiveAction:) withObject:nil afterDelay:1.0f];
//        return;
//    }
    if (((UITextField *)[self.view viewWithTag:41]).text.length == 0) {
        [HUDHelper alert:@"请输入标题"];
        return;
    }
//    if ([((UIButton *)[self.view viewWithTag:21]).titleLabel.text hasPrefix:@"正在定位"]) {
//        [HUDHelper alert:@"正在定位,请稍候"];
//        return;
//    }
    if ([tagStr isEqualToString:@"选择直播标签"]) {
        [HUDHelper alert:@"请选择直播标签"];
        return;
    }
    
//    [[NetworkTool sharedTool] requestWithName:@"创建直播" URLString:APICreateLives parameters:@{@"title":((UITextField *)[self.view viewWithTag:41]).text} method:@"POST" callBack:^(id responseObject) {
//        
//    }];
	__weak OpenLiveViewController *weakself = self;
	
	[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    // 再次检测是否已经登录？是否sig 无效
    [[TCLoginModel sharedInstance] reLogin:^{
		
		[MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *userId = [[TCLoginModel sharedInstance] getLoginParam].identifier;
        NSDictionary *userInfo = GetUserDefaule(USERINFO);
        NSLog(@"用户参数 = %@, %@", userInfo, userId);
        
        TCLiveInfo *publishInfo = [[TCLiveInfo alloc] init];
        publishInfo.userinfo = [[TCLiveUserInfo alloc] init];
        
        publishInfo.userinfo.nickname = userInfo[@"nickname"];
        publishInfo.userinfo.headpic = userInfo[@"face"];
        publishInfo.userinfo.frontcover = userInfo[@"face"]; // 判断什么时候上传完毕 url是否为空
//        publishInfo.money = userInfo[@"money"];
        publishInfo.money = @"0";
        publishInfo.userid = userId;
        publishInfo.title = ((UITextField *)[self.view viewWithTag:41]).text;
        publishInfo.myuserid = userInfo[@"user_id"];
//        publishInfo.userinfo.frontcoverImage = img.image;
//        publishInfo.userinfo.location = ((UIButton *)[self.view viewWithTag:21]).titleLabel.text;
        
        publishInfo.tag = self.tagId;
        publishInfo.isVip = [NSString stringWithFormat:@"%@", userInfo[@"role"]];
//        publishInfo.isLike = @"1";
//        publishInfo.groupid
//        publishInfo.type
//        publishInfo.timestamp
//        publishInfo.fileid
        
        NSDictionary *infoDict = @{@"imId":[userInfo valueForKey:@"user_id"],
                                   @"uid":[userInfo valueForKey:@"user_id"],
                                   @"nickname":userInfo[@"nickname"],
                                   @"headpic":userInfo[@"face"],
                                   @"level":[NSString stringWithFormat:@"%@", [userInfo valueForKey:@"level"]]};
        
        NSLog(@"+++++++publishInfo = %@", publishInfo);
        
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        publishInfo.senderInfo = infoStr;
        
        _liveInfo = publishInfo;
    
        // 跳转	（初步观察从该ViewController开始入手替换直播SDK，但上面也有一些附带信息需要一并替换或保留------Oldfish 2018.7.31）
        //TCPushViewController_LinkMic *pubVC = [[TCPushViewController_LinkMic alloc] initWithPublishInfo:_liveInfo];
		
		//从AgoraLive文件夹的storyboard加载出roomViewController
		UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
		LiveRoomViewController *agoraLiveRoomVC = (LiveRoomViewController *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVC"];
		if (agoraLiveRoomVC) {
			agoraLiveRoomVC.clientRole = weakself.clientRole;
			agoraLiveRoomVC.videoProfile = weakself.videoProfile;
			agoraLiveRoomVC.delegate = weakself;
			agoraLiveRoomVC.liveInfo = _liveInfo;
			
			UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:agoraLiveRoomVC];
			
			// 设置导航背景风格颜色
			nav.navigationBar.barTintColor = UIMainColorRGB;
			[nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:kWhiteColor}];
			
			[self presentViewController:nav animated:YES completion:nil];
			_liveInfo = nil;
		}
		else
		{
			[HUDHelper alert:@"直播间初始化失败"];
		}
		
		
        
        
		
        
    } fail:^(int code, NSString *msg) {
		[MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *err = [NSString stringWithFormat:@"%@(%d)", msg, code];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败"
                                                        message:err
                                                       delegate:self
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil];
        [alert show];
    }];
    
}

- (void)openLocate {
    NSLog(@"首次进入页面或点击定位按钮就打开定位功能");
    
    [((UIButton *)[self.view viewWithTag:21]) setTitle:@" 正在定位" forState:UIControlStateNormal];
    
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestWhenInUseAuthorization]; // 使用程序期间允许访问位置数据（ios8以上需要）
        [self.locationManager startUpdatingLocation];
    }
}

- (void)openLocateAction:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@" 开启定位"]) {
        [self openLocate];
    }
    else
        [sender setTitle:@" 开启定位" forState:UIControlStateNormal];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.mutableTable.hidden = YES;
    return YES;
}

#pragma mark ==========定位功能==========
//定位失败则执行此代理方法
//定位失败弹出提示框,点击"打开定位"按钮,会打开系统的设置,提示打开定位服务
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    /*
     不能定位用户的位置的情况再次进行判断，并给予用户提示
     1、提醒用户检查当前的网络状况
     2、提醒用户打开定位开关
     */
    UIAlertController *alert;
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
        alert = [UIAlertController alertControllerWithTitle:@"LiveDemo需要访问您的位置" message:@"请开\"手机设置\"中的LiveDemo的\"定位权限\"" preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"怎么跳到个人中心");
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([[UIApplication sharedApplication] canOpenURL:url])
            {
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
        alert = [UIAlertController alertControllerWithTitle:@"请检查您的网络状态" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil]];
        
    }
    
    [self presentViewController:alert animated:YES completion:nil];
    
}
//定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *currLocation = [locations lastObject];
    
//    NSLog(@"经度 = %f 纬度 = %f 高度 = %f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
    
    // 根据经纬度反向地理编译出地址信息
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
       
        for (CLPlacemark *placemark in placemarks) {
            NSDictionary *address = [placemark addressDictionary];
            // country 国家 state 省 city 市
//            NSLog(@"-----%@", address);
//            NSLog(@"%@, %@, %@", [address objectForKey:@"Country"],  [address objectForKey:@"State"],  [address objectForKey:@"City"]);
            
            UIButton *btn = (UIButton *)[self.view viewWithTag:21];
            [btn setTitle:[NSString stringWithFormat:@" %@", [address objectForKey:@"City"]] forState:UIControlStateNormal];
            
        }
        
    }];
    
}

#pragma mark ==========照相机相册功能==========
/**
 *  配置图片选择器
 */
-(void)createImgPicker {
    self.picker = [[UIImagePickerController alloc]init];
    self.picker.delegate = self;
    self.picker.allowsEditing = YES;
	self.picker.navigationBar.tintColor = [UIColor blackColor];
}

/**
 *  当用户选取完成后调用
 *
 *  @param picker 图片选择器对象
 *  @param info   返回用户所选择的媒体信息
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // 判断选择的媒体类型是否为图片
    if ([mediaType isEqualToString:@"public.image"]) {
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
            
            //如果是 来自照相机的image，那么先保存
            UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
            UIImageWriteToSavedPhotosAlbum(original_image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            
        }
        
        //获得编辑过的图片
        UIImage *image = [[info objectForKey: @"UIImagePickerControllerEditedImage"] copy];
        
        [self updateCover:image];
        
        UIImageView *img = (UIImageView *)[self.view viewWithTag:1];
        img.image = image;
        
        UIButton *coverBtn = [self.view viewWithTag:61];
        [coverBtn setImage:nil forState:UIControlStateNormal];
        [coverBtn setTitle:@"更改图片" forState:UIControlStateNormal];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
}

/**
 *  将图片保存到iPhone本地相册
 *  UIImage *image            图片对象
 *  id completionTarget       响应方法对象
 *  SEL completionSelector    方法
 *  void *contextInfo
 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"照片保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    
}
//如果这是一个modalViewController，需要dismiss 它发了个cancel消息，必须关闭它
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
   [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark ==========网络请求==========
- (void)updateCover:(UIImage *)img {
    
    
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    NSDictionary *dict = @{
                           @"file[]":@[]
                           };
    
    [afn POST:APIImages parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        // 这里的_photoArr是你存放图片的数组
        NSData *imageData = UIImageJPEGRepresentation(img, 0.8);
        
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        /*
         *该方法的参数
         1. appendPartWithFileData：要上传的照片[二进制流]
         2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
         3. fileName：要保存在服务器上的文件名
         4. mimeType：上传的文件的类型
         */
        [formData appendPartWithFileData:imageData name:@"pic[]" fileName:fileName mimeType:@"image/jpeg"]; //
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
        //        return [obj valueForKey:@"payload"];
        NSArray *imgArr = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"images"];
        NSLog(@"上传图片 success = %@", imgArr);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传图片 failure = %@", error);
        [self presentViewController:[LZCTools AFNErrorAlert:error] animated:YES completion:nil];
    }];
    
}

- (void)GETliveTags {
    
    [[NetworkTool sharedTool] requestWithName:@"获取直播标签" URLString:APITags parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        for (NSDictionary *dict in responseObject[@"data"]) {
            //            NSArray *arr = [[NSArray alloc] initWithObjects:dict[@"name"], dict[@"icon"], nil];
            [self.tagArr addObject:dict];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{

        UIButton *tagBtn = [self.view viewWithTag:51];
        UITextField *titleTF = [self.view viewWithTag:41];

        CGRect rect = self.view.frame;
        CGRect frame = CGRectMake(10, tagBtn.y+tagBtn.height, CGRectGetWidth(rect)-20, SCREEN_HEIGHT-(tagBtn.y+tagBtn.height));
        self.mutableTable = [[YKMultiLevelTableView alloc]
                             initWithFrame:frame
                                     nodes:[self returnData]
                                rootNodeID:@""
                          needPreservation:YES
                               selectBlock:^(YKNodeModel *node) {
                                 NSLog(@"--select node name=%@ id=%@", node.name, node.tagId);

                                 self.tagId = node.tagId;

                                 [tagBtn setTitle:node.name forState:UIControlStateNormal];
                                 CGSize tagSize = [LZCTools textSizeWithText:tagBtn.titleLabel.text font:kUHSystemFontWithSize(16)];
                                 tagBtn.frame = CGRectMake((SCREEN_WIDTH-tagSize.width)/2-5, titleTF.y+titleTF.height+20, tagSize.width+10, tagSize.height+5);
                                 self.mutableTable.hidden = YES;
                             }];
        [self.view addSubview:self.mutableTable];
        self.mutableTable.hidden = YES;
        });
    }];
}

- (NSMutableArray*)returnData{
    
    NSMutableArray *mArr = [[NSMutableArray alloc] init];
    
    NSLog(@"%ld", self.tagArr.count);
    
    for (int i = 0; i < self.tagArr.count; i++) {
        YKNodeModel *node1  = [YKNodeModel nodeWithParentID:@"" name:[self.tagArr[i] valueForKey:@"name"] childrenID:[NSString stringWithFormat:@"%d", i] level:1 isExpand:NO tagId:[self.tagArr[i] valueForKey:@"id"] icon:[self.tagArr[i] valueForKey:@"icon"]];
        [mArr addObject:node1];
        NSArray *arr = [self.tagArr[i] valueForKey:@"children"];
        for (int j = 0; j < arr.count; j++) {
            YKNodeModel *node2 = [YKNodeModel nodeWithParentID:[NSString stringWithFormat:@"%d", i] name:[arr[j] valueForKey:@"name"] childrenID:[NSString stringWithFormat:@"%d%d",i,j] level:2 isExpand:NO tagId:[arr[j] valueForKey:@"id"] icon:[self.tagArr[i] valueForKey:@"icon"]];
            [mArr addObject:node2];
        }
    }
    
    return mArr;

}

//MARK: - AgoraLive delegates
- (void)settingsVC:(SettingsViewController *)settingsVC didSelectProfile:(AgoraVideoProfile)profile {
	self.videoProfile = profile;
	[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)liveVCNeedClose:(LiveRoomViewController *)liveVC {
	[self dismissViewControllerAnimated:YES completion:nil];
}


/**
 懒加载
 */
- (NSMutableArray *)tagArr {
    if (_tagArr == nil) {
        _tagArr = [[NSMutableArray alloc] init];
    }
    return _tagArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
